﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.TownHall.ServiceClient;
using NASA.BeAMartian.Model;
using NASA.BeAMartian.Helper;

namespace NASA.BeAMartian.Views
{
    public partial class SignIn : PhoneApplicationPage
    {
        public THServiceClient client = new THServiceClient();
        ClientState _clientState = new ClientState();

        public SignIn()
        {
            InitializeComponent();

            client.SignInCompleted += new SignInEventHandler(client_SignInCompleted);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            client.Login(tbUsername.Text, pwPassword.Password);
        }

        void client_SignInCompleted(object sender, SignInCompletedEventArgs e)
        {
            Action<SignInCompletedEventArgs> act = new Action<SignInCompletedEventArgs>(DisplayResponse);
            this.Dispatcher.BeginInvoke(act, e);
        }

        void DisplayResponse(SignInCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                ApplicationContext.Instance.UserData = e.UserAccount;
                ApplicationContext.Instance.UserData.DisplayName = tbUsername.Text;

                var store = new PersistentDataStorage();
                store.Backup("User", ApplicationContext.Instance.UserData);

                if (NavigationContext.QueryString.ContainsKey("return"))
                    NavigationService.Navigate(new Uri("/Views/Learn/AskQuestionPage.xaml", UriKind.Relative));
                else
                    this.NavigationService.Navigate(new Uri("/Welcome.xaml", UriKind.Relative));
            }
            else
                MessageBox.Show("Login failed");
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Views/Register.xaml", UriKind.Relative));
        }
    }
}